package com.didispace;

import com.didispace.web.HelloController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
//do have springBootTest annotation
public class HelloApplicationTests2 {

	private MockMvc mvc;

	@Before
	public void setUp() throws Exception {
		mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
	}

	@Test
	public void hello() throws Exception {

		/**
		 * mvc.执行（请求构建器）.andExpect(结果匹配器)
		 * mvc.执行（请求构建器工厂.get().accept()）.andExpect(结果匹配器)
		 * mvc.执行（请求构建器工厂.get().accept()）.andExpect(结果匹配器总厂.结果匹配器工厂.isOk())
		 * 这样可读性是好一些，但是可写行实在太差，特别是对新手来说
		 */
		MockHttpServletRequestBuilder mockHttpServletRequestBuilder =
				MockMvcRequestBuilders.get("/hello")
				.accept(MediaType.APPLICATION_JSON);

		mvc.perform(mockHttpServletRequestBuilder)
				.andExpect(status().isOk())
				.andExpect(content().string(equalTo("Hello World")));
	}

	/**
	 *
	 * step1:创建构建器
	 * step2：执行请求=》获取结果Action
	 * step3：
	 * @throws Exception
	 */
	@Test
	public void hello1() throws Exception {

		MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/hello");
		builder= builder.accept(MediaType.APPLICATION_JSON);

		ResultActions perform = mvc.perform(builder);

		ResultMatcher ok = status().isOk();
		ResultActions resultActions = perform.andExpect(ok);

		ResultMatcher resultMatcher = content().string(equalTo("Hello World"));
		resultActions.andExpect(resultMatcher);
	}

}
